package com.itheima.mp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.PageQuery;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.enums.UserStatus;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.IUserService;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public void reduceBalance(Long id, Integer money) {
        User user = getById(id);
        if (user == null || user.getStatus() == UserStatus.FREEZE) {
            throw new RuntimeException("用户状态异常");
        }

    }

    @Override
    public UserVO querUserAndAddressById(Long userid) {
        User user = getById(userid);
        if (user == null) {
            return null;
        }
        List<Address> addresses = Db.lambdaQuery(Address.class)
                .eq(Address::getUserId, userid).list();
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        userVO.setAddresses(BeanUtil.copyToList(addresses, AddressVO.class));
        return userVO;
    }

    @Override
    public PageDTO<UserVO> queryUsersPage(UserQuery userQuery) {
        String name = userQuery.getName();
        Integer status = userQuery.getStatus();
        Page<User> page = userQuery.toMpPage(new OrderItem("update_time", false));
        lambdaQuery()
                .like(StrUtil.isNotBlank(name), User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .page(page);
        // 返回为空
        if (CollectionUtil.isEmpty(page.getRecords())) {
            return new PageDTO<>(page.getTotal(), page.getPages(), Collections.emptyList());
        }
        List<UserVO> uservos = BeanUtil.copyToList(page.getRecords(), UserVO.class);
        return new PageDTO<>(page.getTotal(), page.getPages(), uservos);
    }
}
